package com.song.server.config.security;

// JWT登录授权过滤器

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Value("${jwt.tokenHead}")
    private String tokenHead;   //Bearer
    @Value("${jwt.tokenHeader}")
    private String tokenHeader; //前端传来的完整token的key值（Authorization）

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserDetailsService userDetailsService;

    // 登录前的判断
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String authHeader = httpServletRequest.getHeader(tokenHeader);

        // 如果存在token，并且是以tokenHead（Bearer）开头
        if (null != authHeader && authHeader.startsWith(tokenHead)) {
            // 截取token
            String token = authHeader.substring(tokenHead.length());

            // 通过token 获取用户名
            String username = jwtTokenUtil.getUserNameFromToken(token);

            // 如果用户名存在，但是未登录
            if (null != username && null == SecurityContextHolder.getContext().getAuthentication()) {
                // 使用自定义的登录逻辑登录
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);

                // 验证token是否有效，重新设置Security对象
                if (jwtTokenUtil.validateToken(token, userDetails)) {
                    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
